package com.talent.jiwen.my;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.PayResult;
import com.talent.jiwen.http.result.RelieveDiscreditResult;
import com.talent.jiwen.http.result.WeChatPayInfo;
import com.talent.jiwen.teacher.CourseAllListFragment;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.talent.jiwen.util.WXPayUtils;
import com.talent.jiwen.util.downtime.DownTimer;
import com.talent.jiwen.util.downtime.DownTimerListener;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;


/**
 * Created by qyqx on 2018/8/10.
 * 支付押金
 */

public class PayDepositActivity extends BaseActivity implements DownTimerListener {

    @BindView(R.id.min_1)
    TextView min_1;
    @BindView(R.id.min_2)
    TextView min_2;
    @BindView(R.id.sec_1)
    TextView sec_1;
    @BindView(R.id.sec_2)
    TextView sec_2;

    @BindView(R.id.ll_wechat)
    RelativeLayout ll_wechat;
    @BindView(R.id.choose_wechat)
    ImageView choose_wechat;
    @BindView(R.id.ll_alipay)
    RelativeLayout ll_alipay;
    @BindView(R.id.choose_alipay)
    ImageView choose_alipay;
    @BindView(R.id.bt_pay)
    TextView bt_pay;

    DownTimer downTimer;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_pay_deposit;
    }

    @Override
    public String titleName() {
        return "支付押金";
    }

    @Override
    protected void initData() {
        downTimer = new DownTimer();
        downTimer.setListener(this);
        downTimer.startMinDown(15 * 60 * 1000);

    }

    private String TAG_CHECKED = "1";
    private int PayStyle = 0;
    private static final int ALIPAY = 1;
    private static final int WECHAT_PAY = 2;

    @OnClick({R.id.ll_wechat, R.id.ll_alipay, R.id.bt_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wechat:
                if (ll_wechat.getTag() == null) {
                    ll_wechat.setTag(TAG_CHECKED);
                    ll_alipay.setTag(null);
                    PayStyle = WECHAT_PAY;
                    choose_wechat.setBackgroundResource(R.mipmap.img_choose);
                    choose_alipay.setBackgroundResource(R.mipmap.img_no_chooae);
                } else {
                    PayStyle = 0;
                    ll_wechat.setTag(null);
                    choose_wechat.setBackgroundResource(R.mipmap.img_no_chooae);
                }
                break;
            case R.id.ll_alipay:
                if (ll_alipay.getTag() == null) {
                    ll_alipay.setTag(TAG_CHECKED);
                    ll_wechat.setTag(null);
                    PayStyle = ALIPAY;
                    choose_wechat.setBackgroundResource(R.mipmap.img_no_chooae);
                    choose_alipay.setBackgroundResource(R.mipmap.img_choose);
                } else {
                    PayStyle = 0;
                    ll_alipay.setTag(null);
                    choose_alipay.setBackgroundResource(R.mipmap.img_no_chooae);
                }
                break;
            case R.id.bt_pay:
//                showToast("请支付");
                if (PayStyle != 0) {
                    studentRelieveDiscredit();

                } else {
                    showToast("请先选择支付方式");
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mBtnLeft.performClick();
    }

    private String orderInfo;//订单信息

    private void toAliPay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayDepositActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();


    }


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayDepositActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayDepositActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    private void studentRelieveDiscredit() {
        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.getUserId());
        map.put("payType", "" + PayStyle);
        Observable observable = ApiFactory.getEducationApiSingleton().studentRelieveDiscredit(SPUtil.getToken(), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<RelieveDiscreditResult>(this) {
            @Override
            protected void _onNext(RelieveDiscreditResult relieveDiscreditResult) {
                if (relieveDiscreditResult != null) {
                    if (PayStyle == WECHAT_PAY) {
                        WeChatPayInfo weChatPayInfo = relieveDiscreditResult.getWeChatPayInfo();
                        if (weChatPayInfo != null) {
                            Constant.PAY_SCENE_FOR_WX = Constant.WX_PAY_FOR_DEPOSIT;
                            WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
                            builder.setAppId(weChatPayInfo.getAppid())
                                    .setPartnerId(weChatPayInfo.getPartnerid())
                                    .setPrepayId(weChatPayInfo.getPrepayid())
                                    .setPackageValue(weChatPayInfo.getPackageValue())
                                    .setNonceStr(weChatPayInfo.getNoncestr())
                                    .setTimeStamp(weChatPayInfo.getTimestamp())
                                    .setSign(weChatPayInfo.getSign())
                                    .build().toWXPayNotSign(PayDepositActivity.this);

                        } else {
                            showToast("支付失败，请稍后重试");
                        }
                    } else if (PayStyle == ALIPAY) {
                        orderInfo = relieveDiscreditResult.getAliPayPrepayId();
                        if (!Validators.isEmpty(orderInfo)) {
                            toAliPay();
                        } else {
                            showToast("支付失败，请稍后重试");
                        }
                    }

                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }


    @Override
    public void onTick(long millisUntilFinished) {

    }

    @Override
    public void onFinish() {
        showToast("支付超时");
        finish();
    }

    @Override
    public void onMinTick(String str) {
        if (!Validators.isEmpty(str) && str.length() == 5) {
            min_1.setText(String.valueOf(str.charAt(0)));
            min_2.setText(String.valueOf(str.charAt(1)));
            sec_1.setText(String.valueOf(str.charAt(3)));
            sec_2.setText(String.valueOf(str.charAt(4)));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downTimer != null) {
            downTimer.stopDown();
        }

    }
}
